package com.woniuxy.commons;

import com.woniuxy.SecurityApplication;
import com.woniuxy.controller.info.SimpleAccountnfo;
import com.woniuxy.dao.ResourceDao;
import com.woniuxy.util.ObjectRedisTemplate;
import com.woniuxy.util.WoniuCopyUtil;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
@Aspect
public class RuleValidateAspect {
	@Resource
	private ResourceDao resourceDao;
	@Autowired
	private ObjectRedisTemplate objectRedisTemplate;
	
	private AntPathMatcher antPathMatcher = new AntPathMatcher();
	
	@Before("@annotation(com.woniuxy.commons.annotation.RuleValidate)")
	public void validateRule() {
		//权限认证
		//获取当前请求的uri
		HttpServletRequest request =((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		String uri = request.getRequestURI();
		String key= (String)request.getSession().getAttribute("LoginUser:info:id");

		//获取用户拥有的uri
		SimpleAccountnfo simpleAccountnfo = objectRedisTemplate.get(key, SimpleAccountnfo.class);
		if(null==simpleAccountnfo){
			System.out.println("iamin");
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		SimpleAccountnfo simpleUserInfo = WoniuCopyUtil.copyOne(authentication.getPrincipal(), SimpleAccountnfo.class);
        List<String> list =resourceDao.getResourceUriList(simpleUserInfo.getAccountId());
        simpleUserInfo.setUris(list);
		request.getSession().setAttribute("LoginUser:info:id","LoginUser:info:id"+simpleUserInfo.getAccountId());
		objectRedisTemplate.opsForValue().setIfAbsent("LoginUser:info:id"+simpleUserInfo.getAccountId(),simpleUserInfo,60*1, TimeUnit.SECONDS);
		simpleAccountnfo=simpleUserInfo;
		}
		System.out.println("imout");

		List<String> resoruces = simpleAccountnfo.getUris();

//		List<String> resoruces = (List<String>)request.getSession().getAttribute("RuleUri");
		boolean b = false;
		for(String ruri : resoruces) {
			if(antPathMatcher.match(ruri, uri)) {
				b = true;
				break;
			}
		}
		if(!b) throw new AccessDeniedException("未授权");
		
	}
	
}